package cn.cnsy123.shorturls.business.filter;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.AntPathMatcher;

import com.alibaba.fastjson.JSON;

import cn.cnsy123.shorturls.api.controller.vo.BaseResponse;
import cn.cnsy123.shorturls.business.localuser.ConsoleUserVo;
import cn.cnsy123.shorturls.business.localuser.RequestContext;
import cn.cnsy123.shorturls.business.util.UserAgentUtil;
import cn.cnsy123.shorturls.constants.SessionInfoConstants;

public class UserLoginRequestFilter implements Filter {
    
    private static final Logger logger = LoggerFactory.getLogger(UserLoginRequestFilter.class);
    
    private static final String LOGIN_PAGE = "/loginPage";
    
    private List<String> excludeUrls = new ArrayList<String>();
    
    private AntPathMatcher antPathMatcher = null;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        antPathMatcher = new AntPathMatcher();
        String excludeUrl = filterConfig.getInitParameter("exclude-url");
        if(StringUtils.isNotBlank(excludeUrl)) {
            logger.info("过滤请求的地址:[{}]",excludeUrl);
            excludeUrls = Arrays.asList(excludeUrl.split(";"));
        }
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest)request;
        HttpServletResponse httpServletResponse = (HttpServletResponse)response;
        
        Object sessionUserInfo = httpServletRequest.getSession().getAttribute(SessionInfoConstants.SESSION_USER_BEAN);
        boolean urlFlag = false;
        for (String excludeUrl : excludeUrls) {
            if(antPathMatcher.match(excludeUrl, httpServletRequest.getServletPath())) {
                urlFlag = true;
                break;
            }
        }
        logger.info("请求地址:{}，拦截状态:[{}]",httpServletRequest.getServletPath(),(urlFlag? "已放行" : "进行拦截"));
        if(sessionUserInfo == null ) {
            RequestContext.clear();
            if(!urlFlag) {
                if(UserAgentUtil.isAjaxRequest(httpServletRequest)) {
                    httpServletResponse.setContentType("application/json;charset=UTF-8"); 
                    PrintWriter writer = httpServletResponse.getWriter();  
                    BaseResponse baseResponse = new BaseResponse(999, "没有登录请重新登录");
                    writer.write(JSON.toJSONString(baseResponse));  
                    writer.flush();
                    writer.close();  
                    httpServletResponse.flushBuffer();  
                }else {
                    httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + LOGIN_PAGE);
                }
                return;
            }
        }
        RequestContext.set((ConsoleUserVo)sessionUserInfo);
        chain.doFilter(httpServletRequest, httpServletResponse);
        
    }

    @Override
    public void destroy() {
        antPathMatcher = null;
    }

}
